<template>
  <div class="menu-management page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">菜单权限管理</h1>
        <p class="page-subtitle">管理系统菜单结构，配置权限路由</p>
      </div>
      <el-button type="primary" @click="openAddMenu" class="add-btn">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
        </svg>
        新增菜单
      </el-button>
    </div>

    <div class="content-card">
      <el-table
        :data="filteredMenus"
        style="width: 100%"
        class="menu-table"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="true"
      >
        <!-- <el-table-column prop="id" label="ID" width="80" /> -->
        <el-table-column prop="name" label="菜单名称" width="200">
          <template #default="scope">
            <span
              :style="{
                paddingLeft: `${
                  scope.row._level ? scope.row._level * 24 : 0
                }px`,
              }"
            >
              {{ scope.row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="menuType" label="类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.menuType === 1" type="info">目录</el-tag>
            <el-tag v-else-if="scope.row.menuType === 2" type="primary"
              >菜单</el-tag
            >
            <el-tag v-else-if="scope.row.menuType === 3" type="success"
              >按钮</el-tag
            >
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" width="200" />
        <el-table-column prop="code" label="权限码" width="160">
          <template #default="scope">
            <el-tag v-if="scope.row.code" type="info">{{
              scope.row.code
            }}</el-tag>
            <span v-else></span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="icon" label="图标" width="100">
          <template #default="scope">
            <div
              v-if="
                scope.row.icon &&
                iconList.find((i) => i.name === scope.row.icon)
              "
              class="icon-container"
            >
              <component
                :is="iconList.find((i) => i.name === scope.row.icon)?.component"
                width="20"
                height="20"
              />
            </div>
            <span v-else class="no-icon"></span>
          </template>
        </el-table-column> -->
        <el-table-column prop="sort" label="排序" width="80" />

        <el-table-column prop="modifiedTime" label="修改时间" width="180" />
        <el-table-column prop="modifiedByName" label="操作人" width="120" />
        <el-table-column label="操作" width="320">
          <template #default="scope">
            <el-button
              size="small"
              type="info"
              @click="showDetail(scope.row)"
              class="action-btn"
            >
              详情
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="openEditMenu(scope.row)"
              class="action-btn"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="openAddSubMenu(scope.row)"
              class="action-btn"
              :disabled="scope.row.menuType === 3"
              :title="scope.row.menuType === 3 ? '按钮类型不可添加子菜单' : ''"
            >
              添加子菜单
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteMenu(scope.row)"
              class="action-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增菜单弹窗 -->
    <el-dialog
      v-model="showAddDialog"
      title="新增菜单"
      width="600px"
      class="menu-dialog"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="addForm.parentId"
            :data="menuTreeData"
            :props="menuTreeProps"
            check-strictly
            placeholder="请选择上级菜单"
            clearable
            class="parent-menu-select"
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-select v-model="addForm.menuType" placeholder="请选择菜单类型">
            <el-option label="目录" :value="1" />
            <el-option label="菜单" :value="2" />
            <el-option label="按钮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限码" prop="code" v-if="addForm.menuType !== 1">
          <el-input v-model="addForm.code" placeholder="请输入权限码" />
        </el-form-item>
        <el-form-item
          label="路由路径"
          prop="path"
          v-if="addForm.menuType === 2"
        >
          <el-input v-model="addForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="addForm.menuType === 1">
          <div class="icon-panel">
            <el-tooltip
              v-for="item in iconList"
              :key="item.name"
              :content="item.name"
              placement="top"
              effect="dark"
            >
              <div
                :class="[
                  'icon-panel-item',
                  addForm.icon === item.name ? 'selected' : '',
                ]"
                @click="addForm.icon = item.name"
              >
                <component :is="item.component" width="22" height="16" />
              </div>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="addForm.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="saveAddMenu" :loading="saving">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑菜单弹窗 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑菜单"
      width="600px"
      class="menu-dialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="editForm.parentId"
            :data="menuTreeData"
            :props="menuTreeProps"
            check-strictly
            placeholder="请选择上级菜单"
            clearable
            class="parent-menu-select"
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-select v-model="editForm.menuType" placeholder="请选择菜单类型">
            <el-option label="目录" :value="1" />
            <el-option label="菜单" :value="2" />
            <el-option label="按钮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限码" prop="code" v-if="editForm.menuType !== 1">
          <el-input v-model="editForm.code" placeholder="请输入权限码" />
        </el-form-item>
        <el-form-item
          label="路由路径"
          prop="path"
          v-if="editForm.menuType === 2"
        >
          <el-input v-model="editForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="editForm.menuType === 1">
          <div class="icon-panel">
            <el-tooltip
              v-for="item in iconList"
              :key="item.name"
              :content="item.name"
              placement="top"
              effect="dark"
            >
              <div
                :class="[
                  'icon-panel-item',
                  editForm.icon === item.name ? 'selected' : '',
                ]"
                @click="editForm.icon = item.name"
              >
                <component :is="item.component" width="22" height="16" />
              </div>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="editForm.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="saveEditMenu" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加子菜单弹窗 -->
    <el-dialog
      v-model="showAddSubDialog"
      title="添加子菜单"
      width="600px"
      class="menu-dialog"
    >
      <el-form
        ref="addSubFormRef"
        :model="addSubForm"
        :rules="addSubRules"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-input :value="addSubParentMenu?.name" disabled />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="addSubForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-select v-model="addSubForm.menuType" placeholder="请选择菜单类型">
            <el-option label="目录" :value="1" />
            <el-option label="菜单" :value="2" />
            <el-option label="按钮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="权限码"
          prop="code"
          v-if="addSubForm.menuType !== 1"
        >
          <el-input v-model="addSubForm.code" placeholder="请输入权限码" />
        </el-form-item>
        <el-form-item
          label="路由路径"
          prop="path"
          v-if="addSubForm.menuType === 2"
        >
          <el-input v-model="addSubForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="addSubForm.menuType === 1">
          <div class="icon-panel">
            <el-tooltip
              v-for="item in iconList"
              :key="item.name"
              :content="item.name"
              placement="top"
              effect="dark"
            >
              <div
                :class="[
                  'icon-panel-item',
                  addSubForm.icon === item.name ? 'selected' : '',
                ]"
                @click="addSubForm.icon = item.name"
              >
                <component :is="item.component" width="22" height="16" />
              </div>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="addSubForm.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddSubDialog = false">取消</el-button>
          <el-button type="primary" @click="saveAddSubMenu" :loading="saving">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="showDetailDialog"
      title="菜单详情"
      width="800px"
      class="detail-dialog"
    >
      <div v-if="detailLoading" class="loading-container">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p class="loading-text">加载中...</p>
      </div>
      <div v-else-if="detailData" class="menu-detail-container">
        <!-- 菜单基本信息卡片 -->
        <div class="detail-card">
          <div class="card-header">
            <div class="header-icon">
              <component
                v-if="
                  detailData.icon &&
                  iconList.find((i) => i.name === detailData.icon)
                "
                :is="
                  iconList.find((i) => i.name === detailData.icon)?.component
                "
                width="24"
                height="24"
              />
              <svg
                v-else
                viewBox="0 0 24 24"
                fill="currentColor"
                width="24"
                height="24"
              >
                <path
                  d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"
                />
              </svg>
            </div>
            <div class="header-content">
              <h3 class="menu-title">{{ detailData.menuName }}</h3>
              <p class="menu-subtitle">{{ detailData.code || "无权限码" }}</p>
            </div>
            <div class="header-status">
              <el-tag
                :type="getMenuTypeTagType(detailData.menuType)"
                size="large"
              >
                {{ getMenuTypeName(detailData.menuType) }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="detail-section">
          <h4 class="section-title">
            <svg
              viewBox="0 0 24 24"
              fill="currentColor"
              width="16"
              height="16"
              style="margin-right: 8px"
            >
              <path
                d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"
              />
            </svg>
            基本信息
          </h4>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">菜单ID</span>
              <span class="info-value">{{ detailData.id }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">菜单名称</span>
              <span class="info-value">{{ detailData.menuName }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">菜单类型</span>
              <span class="info-value">
                <el-tag
                  :type="getMenuTypeTagType(detailData.menuType)"
                  size="small"
                >
                  {{ getMenuTypeName(detailData.menuType) }}
                </el-tag>
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">权限码</span>
              <span class="info-value code-value">{{
                detailData.code || "无"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">路由路径</span>
              <span class="info-value path-value">{{
                detailData.url || "-"
              }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">菜单状态</span>
              <span class="info-value">
                <el-tag
                  :type="detailData.status === 1 ? 'success' : 'danger'"
                  size="small"
                >
                  {{ detailData.status === 1 ? "启用" : "禁用" }}
                </el-tag>
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">上级菜单ID</span>
              <span class="info-value">{{ detailData.pid || "顶级菜单" }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">完全路径</span>
              <span class="info-value path-value">{{ detailData.path }}</span>
            </div>
          </div>
        </div>

        <!-- 图标信息 -->
        <div class="detail-section" v-if="detailData.icon">
          <h4 class="section-title">
            <svg
              viewBox="0 0 24 24"
              fill="currentColor"
              width="16"
              height="16"
              style="margin-right: 8px"
            >
              <path
                d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"
              />
            </svg>
            图标信息
          </h4>
          <div class="icon-display">
            <div class="icon-preview">
              <component
                v-if="iconList.find((i) => i.name === detailData.icon)"
                :is="
                  iconList.find((i) => i.name === detailData.icon)?.component
                "
                width="32"
                height="32"
              />
              <svg
                v-else
                viewBox="0 0 24 24"
                fill="currentColor"
                width="32"
                height="32"
              >
                <path
                  d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"
                />
              </svg>
            </div>
            <div class="icon-info">
              <span class="icon-name">{{ detailData.icon }}</span>
              <span class="icon-path"
                >@/assets/icons/{{ detailData.icon }}.svg</span
              >
            </div>
          </div>
        </div>

        <!-- 时间信息 -->
        <div class="detail-section">
          <h4 class="section-title">
            <svg
              viewBox="0 0 24 24"
              fill="currentColor"
              width="16"
              height="16"
              style="margin-right: 8px"
            >
              <path
                d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"
              />
              <path d="M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z" />
            </svg>
            时间信息
          </h4>
          <div class="time-grid">
            <div class="time-item">
              <span class="time-label">创建时间</span>
              <span class="time-value">{{ detailData.createdTime }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">创建人</span>
              <span class="time-value">{{
                detailData.createdByName || "-"
              }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">修改时间</span>
              <span class="time-value">{{ detailData.modifiedTime }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">修改人</span>
              <span class="time-value">{{
                detailData.modifiedByName || "-"
              }}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-state">
        <el-empty description="暂无数据" :image-size="80" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { postWithAuth } from "@/utils/request";

interface Menu {
  id: number;
  name: string;
  path: string;
  icon?: string;
  parentId?: number;
  sort: number;
  status: string;
  modifiedTime: string;
  modifiedByName: string;
  code: string;
  menuType: number;
  _level?: number;
  children?: Menu[];
}

const loading = ref(false);
const saving = ref(false);

// 弹窗显示控制
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const showAddSubDialog = ref(false);
const showDetailDialog = ref(false);
const detailLoading = ref(false);
const detailData = ref<any>(null);

const menus = ref<Menu[]>([]);

// 菜单排序：filteredMenus、menuTreeData、mapMenuTree等都需按sort升序

// 1. filteredMenus 排序
const filteredMenus = computed(() => {
  // 递归排序
  function sortMenus(list: Menu[]): Menu[] {
    return list
      .slice()
      .sort((a: Menu, b: Menu) => (a.sort ?? 0) - (b.sort ?? 0))
      .map((item: Menu) => ({
        ...item,
        children: item.children ? sortMenus(item.children) : [],
      }));
  }
  return sortMenus(menus.value);
});

// 2. menuTreeData 排序（递归排序）
const menuTreeData = computed(() => {
  function filterNoButtonType(list: Menu[]): Menu[] {
    return list
      .filter((item: Menu) => item.menuType !== 3)
      .sort((a: Menu, b: Menu) => (a.sort ?? 0) - (b.sort ?? 0))
      .map((item: Menu) => ({
        ...item,
        children: item.children ? filterNoButtonType(item.children) : [],
      }));
  }
  return [
    { id: 0, name: "顶级菜单", children: filterNoButtonType(menus.value) },
  ];
});

const menuTreeProps = {
  children: "children",
  label: "name",
  value: "id",
  checkStrictly: true, // 所有节点都可单选
  disabled: false,
};

// 新增菜单表单
const addForm = reactive({
  parentId: undefined as number | undefined,
  name: "",
  path: "",
  icon: "",
  sort: 0,
  status: "active",
  menuType: 2,
  code: "",
});
const addFormRef = ref();

// 编辑菜单表单
const editForm = reactive({
  id: undefined as number | undefined,
  parentId: undefined as number | undefined,
  name: "",
  path: "",
  icon: "",
  sort: 0,
  status: "active",
  menuType: 2,
  code: "",
});
const editFormRef = ref();

// 添加子菜单表单
const addSubForm = reactive({
  parentId: undefined as number | undefined,
  name: "",
  path: "",
  icon: "",
  sort: 0,
  status: "active",
  menuType: 2,
  code: "",
});
const addSubFormRef = ref();
const addSubParentMenu = ref<Menu | null>(null);

// 校验规则
function getRules(form: any) {
  return {
    name: [
      { required: true, message: "请输入菜单名称", trigger: "blur" },
      { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
    ],
    code: [
      {
        required: form.menuType !== 1,
        message: "权限码不能为空",
        trigger: "blur",
      },
    ],
    path: [
      {
        required: form.menuType === 2,
        message: "路由路径不能为空",
        trigger: "blur",
      },
    ],
    sort: [{ required: true, message: "请输入排序值", trigger: "blur" }],
    status: [{ required: true, message: "请选择状态", trigger: "change" }],
  };
}

const addRules = computed(() => getRules(addForm));
const editRules = computed(() => getRules(editForm));
const addSubRules = computed(() => getRules(addSubForm));

// 3. mapMenuTree 赋值sort字段
function mapMenuTree(apiMenus: any[], level = 0): Menu[] {
  return apiMenus.map((item: any) => ({
    id: item.id,
    name: item.menuName,
    path: item.url || "",
    icon: item.icon || "",
    parentId: item.pid || undefined,
    sort: item.sort ?? 0, // 用后端返回的sort
    status: item.status === 1 ? "active" : "inactive",
    modifiedTime: item.modifiedTime || "",
    modifiedByName: item.modifiedByName || "",
    code: item.code || "",
    menuType: item.menuType,
    _level: level,
    children:
      item.children && item.children.length > 0
        ? mapMenuTree(item.children, level + 1)
        : [],
  }));
}

const showDetail = async (row: Menu) => {
  showDetailDialog.value = true;
  detailLoading.value = true;
  try {
    const res = await postWithAuth("/internal/system/manager/getSysMenuById", {
      id: row.id,
    });
    if (res.code === 0 && res.data) {
      detailData.value = res.data;
    } else {
      detailData.value = null;
      ElMessage.error(res.message || "获取详情失败");
      showDetailDialog.value = false;
    }
  } catch (e) {
    detailData.value = null;
    ElMessage.error("获取详情失败");
    showDetailDialog.value = false;
  } finally {
    detailLoading.value = false;
  }
};

// 动态加载SVG
// const svgModules = import.meta.glob("/public/icons/*.svg", { eager: true });

// const iconList = Object.entries(svgModules).map(([path, mod]) => ({
//   name: path.split("/").pop()?.replace(".svg", "") || "",
//   component: (mod as any).default,
// }));
const base = import.meta.env.BASE_URL || "/"; // 获取基础路径
const prefix = import.meta.env.PROD ? "/yfqy-web" : ""; // 生产环境添加前缀

// 方案1：直接使用公共路径（推荐）
const iconList = Object.entries(
  import.meta.glob("/public/icons/*.svg", { eager: true })
).map(([path, mod]) => ({
  name: path.split("/").pop()?.replace(".svg", "") || "",
  component: (mod as any).default,
  // 生产环境访问路径：/aabbc/icons/xxx.svg
  url: `${prefix}${base}icons/${path.split("/").pop()}`,
}));

// 打开新增菜单弹窗
function openAddMenu() {
  Object.assign(addForm, {
    parentId: undefined,
    name: "",
    path: "",
    icon: "",
    sort: 0,
    status: "active",
    menuType: 2,
    code: "",
  });
  showAddDialog.value = true;
}

// 打开编辑菜单弹窗
function openEditMenu(menu: Menu) {
  Object.assign(editForm, {
    id: menu.id,
    parentId: menu.parentId,
    name: menu.name,
    path: menu.path,
    icon: menu.icon || "",
    sort: menu.sort,
    status: menu.status,
    menuType: menu.menuType,
    code: menu.code,
  });
  showEditDialog.value = true;
}

// 打开添加子菜单弹窗
function openAddSubMenu(parentMenu: Menu) {
  Object.assign(addSubForm, {
    parentId: parentMenu.id,
    name: "",
    path: "",
    icon: "",
    sort: 0,
    status: "active",
    menuType: 2,
    code: "",
  });
  addSubParentMenu.value = parentMenu;
  showAddSubDialog.value = true;
}

// 新增菜单保存
async function saveAddMenu() {
  if (!addFormRef.value) return;
  try {
    await addFormRef.value.validate();
    const params: any = {
      menuName: addForm.name,
      code: addForm.menuType !== 1 ? addForm.code : undefined,
      url: addForm.menuType === 2 ? addForm.path : undefined,
      icon: addForm.menuType === 3 ? undefined : addForm.icon, // 按钮类型不传icon
      menuType: addForm.menuType,
      pid: addForm.parentId ?? 0,
      sort: addForm.sort,
    };
    Object.keys(params).forEach(
      (k) => params[k] === undefined && delete params[k]
    );
    const res = await postWithAuth(
      "/internal/system/manager/addSysMenu",
      params
    );
    if (res.code === 0) {
      ElMessage.success("菜单创建成功");
      fetchMenuTree();
      showAddDialog.value = false;
    } else {
      ElMessage.error(res.message || "菜单创建失败");
    }
  } catch (e) {
    // 校验失败
  }
}

// 编辑菜单保存
async function saveEditMenu() {
  if (!editFormRef.value) return;
  try {
    await editFormRef.value.validate();
    const params: any = {
      id: editForm.id?.toString(),
      menuName: editForm.name,
      code: editForm.menuType !== 1 ? editForm.code : undefined,
      url: editForm.menuType === 2 ? editForm.path : undefined,
      icon: editForm.menuType === 3 ? undefined : editForm.icon, // 按钮类型不传icon
      menuType: editForm.menuType,
      pid: editForm.parentId ?? 0,
      sort: editForm.sort,
    };
    Object.keys(params).forEach(
      (k) => params[k] === undefined && delete params[k]
    );
    const res = await postWithAuth(
      "/internal/system/manager/modifySysMenu",
      params
    );
    if (res.code === 0) {
      ElMessage.success("菜单修改成功");
      fetchMenuTree();
      showEditDialog.value = false;
    } else {
      ElMessage.error(res.message || "菜单修改失败");
    }
  } catch (e) {
    // 校验失败
  }
}

// 添加子菜单保存
async function saveAddSubMenu() {
  if (!addSubFormRef.value) return;
  try {
    await addSubFormRef.value.validate();
    const params: any = {
      menuName: addSubForm.name,
      code: addSubForm.menuType !== 1 ? addSubForm.code : undefined,
      url: addSubForm.menuType === 2 ? addSubForm.path : undefined,
      icon: addSubForm.menuType === 3 ? undefined : addSubForm.icon, // 按钮类型不传icon
      menuType: addSubForm.menuType,
      pid: addSubForm.parentId ?? 0,
      sort: addSubForm.sort,
    };
    Object.keys(params).forEach(
      (k) => params[k] === undefined && delete params[k]
    );
    const res = await postWithAuth(
      "/internal/system/manager/addSysMenu",
      params
    );
    if (res.code === 0) {
      ElMessage.success("子菜单创建成功");
      fetchMenuTree();
      showAddSubDialog.value = false;
    } else {
      ElMessage.error(res.message || "子菜单创建失败");
    }
  } catch (e) {
    // 校验失败
  }
}

// 删除菜单
async function deleteMenu(menu: Menu) {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${menu.name}" 吗？${
        menu.children && menu.children.length > 0
          ? "删除前请先删除其所有子菜单！"
          : ""
      }`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await postWithAuth(
      "/internal/system/manager/deleteSysMenu",
      {
        id: menu.id,
      }
    );

    if (response.code === 0) {
      ElMessage.success("菜单删除成功");
      fetchMenuTree(); // 刷新菜单列表
    } else {
      ElMessage.error(response.message || "菜单删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除菜单失败:", error);
      ElMessage.error("删除菜单失败");
    }
  }
}

// 获取菜单树数据
async function fetchMenuTree() {
  loading.value = true;
  try {
    const res = await postWithAuth(
      "/internal/system/manager/getSysMenuTree",
      {}
    );
    if (res.code === 0 && Array.isArray(res.data)) {
      menus.value = mapMenuTree(res.data);
    } else {
      ElMessage.error(res.message || "获取菜单数据失败");
    }
  } catch (e: any) {
    ElMessage.error(e.message || "请求菜单数据异常");
  } finally {
    loading.value = false;
  }
}

// 获取菜单类型名称
const getMenuTypeName = (menuType: number): string => {
  switch (menuType) {
    case 1:
      return "目录";
    case 2:
      return "菜单";
    case 3:
      return "按钮";
    default:
      return "未知";
  }
};

// 获取菜单类型标签类型
const getMenuTypeTagType = (menuType: number): string => {
  switch (menuType) {
    case 1:
      return "info";
    case 2:
      return "primary";
    case 3:
      return "success";
    default:
      return "info";
  }
};

onMounted(() => {
  fetchMenuTree();
});
</script>

<style scoped>
.menu-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  /* background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); */
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2d3748;
  margin: 0 0 8px 0;
}

.page-subtitle {
  color: #718096;
  margin: 0;
  font-size: 16px;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
}

.btn-icon {
  width: 16px;
  height: 16px;
}

.content-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.search-icon {
  width: 16px;
  height: 16px;
  color: #a0aec0;
}

.menu-table {
  margin-bottom: 24px;
}

.menu-icon {
  width: 16px;
  height: 16px;
  color: #667eea;
}

.no-icon {
  color: #a0aec0;
  font-size: 12px;
}

.icon-container {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background-color: #6c757d;
  border-radius: 6px;
  padding: 6px;
  transition: all 0.3s ease;
}

.icon-container:hover {
  background-color: #5a6268;
  transform: scale(1.05);
}

.icon-container svg {
  width: 20px;
  height: 20px;
  filter: brightness(0) invert(1);
}

.action-btn {
  margin-right: 8px;
}

.action-btn:last-child {
  margin-right: 0;
}

.menu-dialog {
  border-radius: 12px;
}

.parent-menu-select {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.icon-panel {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 4px;
}
.icon-panel-item {
  border: 2px solid transparent;
  border-radius: 8px;
  padding: 6px;
  cursor: pointer;
  transition: border 0.2s;
  background: #6c757d;
}
.icon-panel-item.selected {
  border-color: #409eff;
  background: #495057;
}
.icon-panel-item:hover {
  border-color: #a0cfff;
  background: #5a6268;
}

/* 平板端适配 */
@media (max-width: 1024px) {
  .menu-management {
    padding: 20px;
  }

  .page-header {
    padding: 20px;
  }

  .page-title {
    font-size: 24px;
  }

  .page-subtitle {
    font-size: 14px;
  }

  .content-card {
    padding: 20px;
  }

  .search-section {
    gap: 12px;
  }

  .search-input {
    max-width: 250px;
  }
}

/* 手机端适配 */
@media (max-width: 768px) {
  .menu-management {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 20px;
  }

  .page-title {
    font-size: 20px;
    margin-bottom: 6px;
  }

  .page-subtitle {
    font-size: 13px;
  }

  .add-btn {
    align-self: flex-start;
    padding: 10px 20px;
  }

  .content-card {
    padding: 16px;
    border-radius: 10px;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .search-input {
    max-width: none;
  }

  .menu-table {
    margin-bottom: 20px;
  }

  /* 表格在手机端的特殊处理 */
  .menu-table :deep(.el-table) {
    font-size: 12px;
  }

  .menu-table :deep(.el-table th) {
    padding: 8px 4px;
  }

  .menu-table :deep(.el-table td) {
    padding: 8px 4px;
  }

  .action-btn {
    margin-right: 4px;
    margin-bottom: 4px;
    padding: 4px 8px;
    font-size: 11px;
  }

  .menu-icon {
    width: 14px;
    height: 14px;
  }

  .icon-container {
    width: 28px;
    height: 28px;
    padding: 4px;
  }

  .icon-container svg {
    width: 18px;
    height: 18px;
  }

  .no-icon {
    font-size: 10px;
  }

  .menu-dialog {
    width: 90% !important;
    max-width: 400px;
  }

  .dialog-footer {
    gap: 8px;
  }

  .dialog-footer .el-button {
    padding: 8px 16px;
    font-size: 13px;
  }
}

/* 小屏手机适配 */
@media (max-width: 480px) {
  .menu-management {
    padding: 12px;
  }

  .page-header {
    padding: 16px;
    gap: 12px;
  }

  .page-title {
    font-size: 18px;
  }

  .page-subtitle {
    font-size: 12px;
  }

  .add-btn {
    padding: 8px 16px;
    font-size: 13px;
  }

  .btn-icon {
    width: 14px;
    height: 14px;
  }

  .content-card {
    padding: 12px;
  }

  .search-section {
    gap: 8px;
  }

  .menu-table :deep(.el-table) {
    font-size: 11px;
  }

  .menu-table :deep(.el-table th) {
    padding: 6px 2px;
  }

  .menu-table :deep(.el-table td) {
    padding: 6px 2px;
  }

  .action-btn {
    padding: 3px 6px;
    font-size: 10px;
    margin-right: 2px;
  }

  .menu-icon {
    width: 12px;
    height: 12px;
  }

  .icon-container {
    width: 24px;
    height: 24px;
    padding: 3px;
  }

  .icon-container svg {
    width: 16px;
    height: 16px;
  }

  .no-icon {
    font-size: 9px;
  }

  .menu-dialog {
    width: 95% !important;
    max-width: 350px;
  }
}

/* 横屏手机适配 */
@media (max-height: 500px) and (orientation: landscape) {
  .menu-management {
    padding: 12px;
  }

  .page-header {
    padding: 12px 20px;
    margin-bottom: 16px;
  }

  .page-title {
    font-size: 16px;
    margin-bottom: 4px;
  }

  .page-subtitle {
    font-size: 11px;
  }

  .add-btn {
    padding: 6px 12px;
    font-size: 12px;
  }

  .content-card {
    padding: 12px;
  }

  .search-section {
    margin-bottom: 16px;
  }

  .menu-table {
    margin-bottom: 16px;
  }
}

/* 表格响应式处理 */
@media (max-width: 768px) {
  /* 隐藏某些列在手机端 */
  .menu-table :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }

  /* 确保表格可以横向滚动 */
  .menu-table :deep(.el-table) {
    min-width: 600px;
  }

  /* 树形表格在手机端的特殊处理 */
  .menu-table :deep(.el-table__expand-icon) {
    font-size: 12px;
  }

  .menu-table :deep(.el-table__expand-icon .el-icon) {
    font-size: 12px;
  }
}

/* 对话框响应式处理 */
@media (max-width: 768px) {
  .menu-dialog :deep(.el-dialog__body) {
    padding: 16px;
  }

  .menu-dialog :deep(.el-form-item__label) {
    font-size: 13px;
    line-height: 1.4;
  }

  .menu-dialog :deep(.el-input__inner) {
    font-size: 14px;
  }

  .menu-dialog :deep(.el-textarea__inner) {
    font-size: 14px;
  }

  .menu-dialog :deep(.el-select) {
    font-size: 14px;
  }

  .menu-dialog :deep(.el-input-number) {
    font-size: 14px;
  }

  .menu-dialog :deep(.el-tree-select) {
    font-size: 14px;
  }
}

/* 树形选择器响应式处理 */
@media (max-width: 480px) {
  .menu-dialog :deep(.el-tree-select .el-tree-node__content) {
    height: 28px;
    font-size: 12px;
  }

  .menu-dialog :deep(.el-tree-select .el-tree-node__expand-icon) {
    font-size: 11px;
  }

  .menu-dialog :deep(.el-form-item__label) {
    font-size: 12px;
  }

  .menu-dialog :deep(.el-input__inner),
  .menu-dialog :deep(.el-textarea__inner),
  .menu-dialog :deep(.el-select),
  .menu-dialog :deep(.el-input-number),
  .menu-dialog :deep(.el-tree-select) {
    font-size: 13px;
  }
}

/* 树形表格特殊处理 */
@media (max-width: 768px) {
  .menu-table :deep(.el-table__row) {
    height: 40px;
  }

  .menu-table :deep(.el-table__cell) {
    padding: 6px 4px;
  }

  .menu-table :deep(.el-table__expand-icon) {
    width: 16px;
    height: 16px;
  }
}

@media (max-width: 480px) {
  .menu-table :deep(.el-table__row) {
    height: 36px;
  }

  .menu-table :deep(.el-table__cell) {
    padding: 4px 2px;
  }

  .menu-table :deep(.el-table__expand-icon) {
    width: 14px;
    height: 14px;
  }
}

/* 菜单详情弹窗样式 */
.detail-dialog {
  border-radius: 12px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-icon {
  font-size: 32px;
  color: #667eea;
  margin-bottom: 16px;
}

.loading-text {
  color: #718096;
  font-size: 14px;
  margin: 0;
}

.menu-detail-container {
  padding: 0;
}

.detail-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  color: white;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.header-content {
  flex: 1;
}

.menu-title {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 700;
  color: white;
}

.menu-subtitle {
  margin: 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.header-status {
  margin-left: auto;
}

.detail-section {
  background: white;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  overflow: hidden;
  margin-bottom: 20px;
}

.section-title {
  margin: 0;
  color: #2d3748;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  padding: 20px 24px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
  padding: 24px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f7fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.info-label {
  font-weight: 600;
  color: #4a5568;
  min-width: 80px;
  margin-right: 16px;
  font-size: 14px;
}

.info-value {
  color: #2d3748;
  flex: 1;
  font-size: 14px;
}

.code-value {
  font-family: "Courier New", monospace;
  background: #edf2f7;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 13px;
}

.path-value {
  font-family: "Courier New", monospace;
  background: #f0f9ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 13px;
  color: #0369a1;
}

.icon-display {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 24px;
}

.icon-preview {
  width: 64px;
  height: 64px;
  background: #f7fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.icon-name {
  font-weight: 600;
  color: #2d3748;
  font-size: 14px;
}

.icon-path {
  font-family: "Courier New", monospace;
  color: #718096;
  font-size: 12px;
  background: #f7fafc;
  padding: 2px 6px;
  border-radius: 4px;
}

.time-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  padding: 24px;
}

.time-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f7fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.time-label {
  font-weight: 600;
  color: #4a5568;
  min-width: 80px;
  margin-right: 16px;
  font-size: 14px;
}

.time-value {
  color: #2d3748;
  flex: 1;
  font-size: 14px;
}

.empty-state {
  padding: 40px 24px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-dialog {
    width: 95% !important;
    max-width: 600px;
  }

  .detail-card {
    padding: 20px;
    margin-bottom: 20px;
  }

  .card-header {
    gap: 12px;
  }

  .header-icon {
    width: 40px;
    height: 40px;
  }

  .menu-title {
    font-size: 20px;
  }

  .menu-subtitle {
    font-size: 13px;
  }

  .section-title {
    padding: 16px 20px;
    font-size: 14px;
  }

  .info-grid {
    grid-template-columns: 1fr;
    gap: 12px;
    padding: 20px;
  }

  .info-item {
    padding: 12px;
  }

  .info-label {
    min-width: 70px;
    font-size: 13px;
  }

  .info-value {
    font-size: 13px;
  }

  .icon-display {
    padding: 20px;
    flex-direction: column;
    align-items: flex-start;
  }

  .icon-preview {
    width: 48px;
    height: 48px;
  }

  .time-grid {
    grid-template-columns: 1fr;
    gap: 12px;
    padding: 20px;
  }

  .time-item {
    padding: 12px;
  }

  .time-label {
    min-width: 70px;
    font-size: 13px;
  }

  .time-value {
    font-size: 13px;
  }
}
</style>
